﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using TopologySearch.LoopSearch;

namespace TopologySearch
{
	public partial class OffsetTestForm : System.Windows.Forms.Form
	{
		public double Offset
		{
			get
			{
				return Common.MMToFeet(Convert.ToDouble(this.m_Offset));
			}
		}

		public OffsetTestForm()
		{
			this.InitializeComponent();
		}

		private void OffsetTestForm_Load(object sender, EventArgs e)
		{
			this.ReadData();
		}

		private void OffsetTestForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (!this.OffsetValueIsValidating())
			{
				e.Cancel = true;
				MessageBox.Show("'OffsetValue' is not validting");
				return;
			}
			this.SaveData();
		}

		private void ReadData()
		{
			string path = Path.GetTempPath() + "OffsetTestForm.dat";
			if (!File.Exists(path))
			{
				base.StartPosition = FormStartPosition.CenterScreen;
				this.m_Offset = "0";
				this.tbOffsetValue.Text = this.m_Offset;
				return;
			}
			base.StartPosition = FormStartPosition.Manual;
			FileStream fileStream = new FileStream(path, FileMode.Open);
			StreamReader streamReader = new StreamReader(fileStream);
			streamReader.BaseStream.Seek(0L, SeekOrigin.Begin);
			int x = Convert.ToInt32(streamReader.ReadLine());
			int y = Convert.ToInt32(streamReader.ReadLine());
			base.Location = new System.Drawing.Point(x, y);
			this.m_Offset = streamReader.ReadLine();
			this.tbOffsetValue.Text = this.m_Offset;
			streamReader.Close();
			fileStream.Close();
		}

		private void SaveData()
		{
			FileStream fileStream = new FileStream(Path.GetTempPath() + "OffsetTestForm.dat", FileMode.Create);
			StreamWriter streamWriter = new StreamWriter(fileStream);
			streamWriter.WriteLine(base.Location.X);
			streamWriter.WriteLine(base.Location.Y);
			streamWriter.WriteLine(this.m_Offset);
			streamWriter.Flush();
			streamWriter.Close();
			fileStream.Close();
		}

		private bool OffsetValueIsValidating()
		{
			bool result;
			try
			{
				double.Parse(this.tbOffsetValue.Text);
				this.m_Offset = this.tbOffsetValue.Text;
				result = true;
			}
			catch (Exception)
			{
				this.tbOffsetValue.Text = this.m_Offset;
				result = false;
			}
			return result;
		}

		private string m_Offset = "";
	}
}
